Merge "Fix "UTPage" creation in tests"
authorjenkins-bot <jenkins-bot@gerrit.wikimedia.org>
Tue, 22 Apr 2014 17:56:32 +0000 (17:56 +0000)
committerGerrit Code Review <gerrit@wikimedia.org>
Tue, 22 Apr 2014 17:56:32 +0000 (17:56 +0000)
1  2 
tests/phpunit/MediaWikiTestCase.php

@@@ -1,9 -1,9 +1,9 @@@
  <?php
  
 +/**
 + * @since 1.18
 + */
  abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
 -      public $suite;
 -      public $regex = '';
 -      public $runDisabled = false;
  
        /**
         * $called tracks whether the setUp and tearDown method has been called.
        private $called = array();
  
        /**
 -       * @var Array of TestUser
 +       * @var TestUser[]
 +       * @since 1.20
         */
        public static $users;
  
        /**
         * @var DatabaseBase
 +       * @since 1.18
         */
        protected $db;
 +
 +      /**
 +       * @var array
 +       * @since 1.19
 +       */
        protected $tablesUsed = array(); // tables with data
  
        private static $useTemporaryTables = true;
@@@ -55,7 -48,7 +55,7 @@@
         *
         * @var array
         */
 -      private $tmpfiles = array();
 +      private $tmpFiles = array();
  
        /**
         * Holds original values of MediaWiki configuration settings
        const DB_PREFIX = 'unittest_';
        const ORA_DB_PREFIX = 'ut_';
  
 +      /**
 +       * @var array
 +       * @since 1.18
 +       */
        protected $supportedDBs = array(
                'mysql',
                'sqlite',
                'oracle'
        );
  
 -      function __construct( $name = null, array $data = array(), $dataName = '' ) {
 +      public function __construct( $name = null, array $data = array(), $dataName = '' ) {
                parent::__construct( $name, $data, $dataName );
  
                $this->backupGlobals = false;
                $this->backupStaticAttributes = false;
        }
  
 -      function run( PHPUnit_Framework_TestResult $result = null ) {
 +      public function run( PHPUnit_Framework_TestResult $result = null ) {
                /* Some functions require some kind of caching, and will end up using the db,
                 * which we can't allow, as that would open a new connection for mysql.
                 * Replace with a HashBag. They would not be going to persist anyway.
                }
        }
  
 -      function usesTemporaryTables() {
 +      /**
 +       * @since 1.21
 +       *
 +       * @return bool
 +       */
 +      public function usesTemporaryTables() {
                return self::$useTemporaryTables;
        }
  
        /**
 -       * obtains a new temporary file name
 +       * Obtains a new temporary file name
         *
         * The obtained filename is enlisted to be removed upon tearDown
         *
 -       * @return string: absolute name of the temporary file
 +       * @since 1.20
 +       *
 +       * @return string Absolute name of the temporary file
         */
        protected function getNewTempFile() {
 -              $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
 -              $this->tmpfiles[] = $fname;
 +              $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
 +              $this->tmpFiles[] = $fileName;
  
 -              return $fname;
 +              return $fileName;
        }
  
        /**
         * The obtained directory is enlisted to be removed (recursively with all its contained
         * files) upon tearDown.
         *
 -       * @return string: absolute name of the temporary directory
 +       * @since 1.20
 +       *
 +       * @return string Absolute name of the temporary directory
         */
        protected function getNewTempDirectory() {
                // Starting of with a temporary /file/.
 -              $fname = $this->getNewTempFile();
 +              $fileName = $this->getNewTempFile();
  
                // Converting the temporary /file/ to a /directory/
                //
                // The following is not atomic, but at least we now have a single place,
                // where temporary directory creation is bundled and can be improved
 -              unlink( $fname );
 -              $this->assertTrue( wfMkdirParents( $fname ) );
 +              unlink( $fileName );
 +              $this->assertTrue( wfMkdirParents( $fileName ) );
  
 -              return $fname;
 +              return $fileName;
        }
  
 -      /**
 -       * setUp and tearDown should (where significant)
 -       * happen in reverse order.
 -       */
        protected function setUp() {
                wfProfileIn( __METHOD__ );
                parent::setUp();
  
                $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
  
 -              /*
 -              // @todo global variables to restore for *every* test
 -              array(
 -                      'wgLang',
 -                      'wgContLang',
 -                      'wgLanguageCode',
 -                      'wgUser',
 -                      'wgTitle',
 -              );
 -              */
 -
                // Cleaning up temporary files
 -              foreach ( $this->tmpfiles as $fname ) {
 -                      if ( is_file( $fname ) || ( is_link( $fname ) ) ) {
 -                              unlink( $fname );
 -                      } elseif ( is_dir( $fname ) ) {
 -                              wfRecursiveRemoveDir( $fname );
 +              foreach ( $this->tmpFiles as $fileName ) {
 +                      if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
 +                              unlink( $fileName );
 +                      } elseif ( is_dir( $fileName ) ) {
 +                              wfRecursiveRemoveDir( $fileName );
                        }
                }
  
                wfProfileIn( __METHOD__ );
  
                // Cleaning up temporary files
 -              foreach ( $this->tmpfiles as $fname ) {
 -                      if ( is_file( $fname ) || ( is_link( $fname ) ) ) {
 -                              unlink( $fname );
 -                      } elseif ( is_dir( $fname ) ) {
 -                              wfRecursiveRemoveDir( $fname );
 +              foreach ( $this->tmpFiles as $fileName ) {
 +                      if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
 +                              unlink( $fileName );
 +                      } elseif ( is_dir( $fileName ) ) {
 +                              wfRecursiveRemoveDir( $fileName );
                        }
                }
  
        }
  
        /**
 -       * Individual test functions may override globals (either directly or through this
 -       * setMwGlobals() function), however one must call this method at least once for
 -       * each key within the setUp().
 -       * That way the key is added to the array of globals that will be reset afterwards
 -       * in the tearDown(). And, equally important, that way all other tests are executed
 -       * with the same settings (instead of using the unreliable local settings for most
 -       * tests and fix it only for some tests).
 +       * Sets a global, maintaining a stashed version of the previous global to be
 +       * restored in tearDown
 +       *
 +       * The key is added to the array of globals that will be reset afterwards
 +       * in the tearDown().
         *
         * @example
         * <code>
         *  of key/value pairs.
         * @param mixed $value Value to set the global to (ignored
         *  if an array is given as first argument).
 +       *
 +       * @since 1.21
         */
        protected function setMwGlobals( $pairs, $value = null ) {
 -
 -              // Normalize (string, value) to an array
                if ( is_string( $pairs ) ) {
                        $pairs = array( $pairs => $value );
                }
  
 +              $this->stashMwGlobals( array_keys( $pairs ) );
 +
                foreach ( $pairs as $key => $value ) {
 +                      $GLOBALS[$key] = $value;
 +              }
 +      }
 +
 +      /**
 +       * Stashes the global, will be restored in tearDown()
 +       *
 +       * Individual test functions may override globals through the setMwGlobals() function
 +       * or directly. When directly overriding globals their keys should first be passed to this
 +       * method in setUp to avoid breaking global state for other tests
 +       *
 +       * That way all other tests are executed with the same settings (instead of using the
 +       * unreliable local settings for most tests and fix it only for some tests).
 +       *
 +       * @param array|string $globalKeys Key to the global variable, or an array of keys.
 +       *
 +       * @throws Exception when trying to stash an unset global
 +       * @since 1.23
 +       */
 +      protected function stashMwGlobals( $globalKeys ) {
 +              if ( is_string( $globalKeys ) ) {
 +                      $globalKeys = array( $globalKeys );
 +              }
 +
 +              foreach ( $globalKeys as $globalKey ) {
                        // NOTE: make sure we only save the global once or a second call to
                        // setMwGlobals() on the same global would override the original
                        // value.
 -                      if ( !array_key_exists( $key, $this->mwGlobals ) ) {
 +                      if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
 +                              if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
 +                                      throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
 +                              }
                                // NOTE: we serialize then unserialize the value in case it is an object
                                // this stops any objects being passed by reference. We could use clone
                                // and if is_object but this does account for objects within objects!
 -                              try{
 -                                      $this->mwGlobals[$key] = unserialize( serialize( $GLOBALS[$key] ) );
 +                              try {
 +                                      $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
                                }
 -                              // NOTE; some things such as Closures are not serializable
 -                              // in this case just set the value!
 -                              catch( Exception $e ) {
 -                                      $this->mwGlobals[$key] = $GLOBALS[$key];
 +                                      // NOTE; some things such as Closures are not serializable
 +                                      // in this case just set the value!
 +                              catch ( Exception $e ) {
 +                                      $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
                                }
                        }
 -
 -                      // Override the global
 -                      $GLOBALS[$key] = $value;
                }
        }
  
         * Useful for setting some entries in a configuration array, instead of
         * setting the entire array.
         *
 -       * @param String $name The name of the global, as in wgFooBar
 -       * @param Array $values The array containing the entries to set in that global
 +       * @param string $name The name of the global, as in wgFooBar
 +       * @param array $values The array containing the entries to set in that global
         *
         * @throws MWException if the designated global is not an array.
 +       *
 +       * @since 1.21
         */
        protected function mergeMwGlobalArrayValue( $name, $values ) {
                if ( !isset( $GLOBALS[$name] ) ) {
                $this->setMwGlobals( $name, $merged );
        }
  
 -      function dbPrefix() {
 +      /**
 +       * @return string
 +       * @since 1.18
 +       */
 +      public function dbPrefix() {
                return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
        }
  
 -      function needsDB() {
 +      /**
 +       * @return bool
 +       * @since 1.18
 +       */
 +      public function needsDB() {
                # if the test says it uses database tables, it needs the database
                if ( $this->tablesUsed ) {
                        return true;
        /**
         * Stub. If a test needs to add additional data to the database, it should
         * implement this method and do so
 +       *
 +       * @since 1.18
         */
 -      function addDBData() {
 +      public function addDBData() {
        }
  
        private function addCoreDBData() {
 -              # disabled for performance
 -              #$this->tablesUsed[] = 'page';
 -              #$this->tablesUsed[] = 'revision';
 -
                if ( $this->db->getType() == 'oracle' ) {
  
                        # Insert 0 user to prevent FK violations
  
                //Make 1 page with 1 revision
                $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
-               if ( !$page->getId() == 0 ) {
+               if ( $page->getId() == 0 ) {
                        $page->doEditContent(
                                new WikitextContent( 'UTContent' ),
                                'UTPageSummary',
         * Restores MediaWiki to using the table set (table prefix) it was using before
         * setupTestDB() was called. Useful if we need to perform database operations
         * after the test run has finished (such as saving logs or profiling info).
 +       *
 +       * @since 1.21
         */
        public static function teardownTestDB() {
                if ( !self::$dbSetup ) {
         * This is used to generate a dummy table set, typically consisting of temporary
         * tables, that will be used by tests instead of the original wiki database tables.
         *
 +       * @since 1.21
 +       *
         * @note: the original table prefix is stored in self::$oldTablePrefix. This is used
         * by teardownTestDB() to return the wiki to using the original table set.
         *
         * even if using different parameters.
         *
         * @param DatabaseBase $db The database connection
 -       * @param String $prefix The prefix to use for the new table set (aka schema).
 +       * @param string $prefix The prefix to use for the new table set (aka schema).
         *
         * @throws MWException if the database table prefix is already $prefix
         */
        public static function setupTestDB( DatabaseBase $db, $prefix ) {
                global $wgDBprefix;
                if ( $wgDBprefix === $prefix ) {
 -                      throw new MWException( 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
 +                      throw new MWException(
 +                              'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
                }
  
                if ( self::$dbSetup ) {
                }
        }
  
 -      function __call( $func, $args ) {
 +      /**
 +       * @since 1.18
 +       *
 +       * @param string $func
 +       * @param array $args
 +       *
 +       * @return mixed
 +       * @throws MWException
 +       */
 +      public function __call( $func, $args ) {
                static $compatibility = array(
 -                      'assertInternalType' => 'assertType',
 -                      'assertNotInternalType' => 'assertNotType',
 -                      'assertInstanceOf' => 'assertType',
 -                      'assertEmpty' => 'assertEmpty2',
 +                      'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
                );
  
 -              if ( method_exists( $this->suite, $func ) ) {
 -                      return call_user_func_array( array( $this->suite, $func ), $args );
 -              } elseif ( isset( $compatibility[$func] ) ) {
 +              if ( isset( $compatibility[$func] ) ) {
                        return call_user_func_array( array( $this, $compatibility[$func] ), $args );
                } else {
                        throw new MWException( "Called non-existant $func method on "
                }
        }
  
 +      /**
 +       * Used as a compatibility method for phpunit < 3.7.32
 +       * @param string $value
 +       * @param string $msg
 +       */
        private function assertEmpty2( $value, $msg ) {
                return $this->assertTrue( $value == '', $msg );
        }
                return strpos( $table, 'unittest_' ) !== 0;
        }
  
 +      /**
 +       * @since 1.18
 +       *
 +       * @param DataBaseBase $db
 +       *
 +       * @return array
 +       */
        public static function listTables( $db ) {
                global $wgDBprefix;
  
                return $tables;
        }
  
 +      /**
 +       * @throws MWException
 +       * @since 1.18
 +       */
        protected function checkDbIsSupported() {
                if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
                        throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
                }
        }
  
 +      /**
 +       * @since 1.18
 +       * @param string $offset
 +       * @return mixed
 +       */
        public function getCliArg( $offset ) {
 -
                if ( isset( MediaWikiPHPUnitCommand::$additionalOptions[$offset] ) ) {
                        return MediaWikiPHPUnitCommand::$additionalOptions[$offset];
                }
        }
  
 +      /**
 +       * @since 1.18
 +       * @param string $offset
 +       * @param mixed $value
 +       */
        public function setCliArg( $offset, $value ) {
 -
                MediaWikiPHPUnitCommand::$additionalOptions[$offset] = $value;
        }
  
        /**
         * Don't throw a warning if $function is deprecated and called later
         *
 -       * @param $function String
 -       * @return null
 +       * @since 1.19
 +       *
 +       * @param string $function
         */
 -      function hideDeprecated( $function ) {
 +      public function hideDeprecated( $function ) {
                wfSuppressWarnings();
                wfDeprecated( $function );
                wfRestoreWarnings();
         *
         * @since 1.20
         *
 -       * @param $table String|Array the table(s) to query
 -       * @param $fields String|Array the columns to include in the result (and to sort by)
 -       * @param $condition String|Array "where" condition(s)
 -       * @param $expectedRows Array - an array of arrays giving the expected rows.
 +       * @param string|array $table The table(s) to query
 +       * @param string|array $fields The columns to include in the result (and to sort by)
 +       * @param string|array $condition "where" condition(s)
 +       * @param array $expectedRows An array of arrays giving the expected rows.
         *
 -       * @throws MWException if this test cases's needsDB() method doesn't return true.
 +       * @throws MWException If this test cases's needsDB() method doesn't return true.
         *         Test cases can use "@group Database" to enable database test support,
         *         or list the tables under testing in $this->tablesUsed, or override the
         *         needsDB() method.
         *
         * @param array $expected
         * @param array $actual
 -       * @param boolean $ordered If the order of the values should match
 -       * @param boolean $named If the keys should match
 +       * @param bool $ordered If the order of the values should match
 +       * @param bool $named If the keys should match
         */
        protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
                if ( !$ordered ) {
         *
         * @since 1.20
         *
 -       * @param String $expected HTML on oneline
 -       * @param String $actual HTML on oneline
 -       * @param String $msg Optional message
 +       * @param string $expected HTML on oneline
 +       * @param string $actual HTML on oneline
 +       * @param string $msg Optional message
         */
        protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
                $expected = str_replace( '>', ">\n", $expected );
         *
         * @since 1.20
         *
 -       * @param $r mixed the array to remove string keys from.
 +       * @param mixed $r The array to remove string keys from.
         */
        protected static function stripStringKeys( &$r ) {
                if ( !is_array( $r ) ) {
  
        /**
         * Returns the ID of a namespace that defaults to Wikitext.
 -       * Throws an MWException if there is none.
         *
 -       * @return int the ID of the wikitext Namespace
 +       * @throws MWException If there is none.
 +       * @return int The ID of the wikitext Namespace
         * @since 1.21
         */
        protected function getDefaultWikitextNS() {
         * test whenever it is not loaded.
         *
         * @since 1.21
 +       * @param string $extName
 +       * @return bool
         */
        protected function checkPHPExtension( $extName ) {
                $loaded = extension_loaded( $extName );
         * then calls assertValidHtmlDocument().
         * The snippet is expected to be HTML 5.
         *
 -       * @note: Will mark the test as skipped if the "tidy" module is not installed.
 -       * @note: This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
 +       * @since 1.23
 +       *
 +       * @note Will mark the test as skipped if the "tidy" module is not installed.
 +       * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
         *        when automatic tidying is disabled.
         *
         * @param string $html An HTML snippet (treated as the contents of the body tag).
        /**
         * Asserts that the given string is valid HTML document.
         *
 -       * @note: Will mark the test as skipped if the "tidy" module is not installed.
 -       * @note: This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
 +       * @since 1.23
 +       *
 +       * @note Will mark the test as skipped if the "tidy" module is not installed.
 +       * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
         *        when automatic tidying is disabled.
         *
         * @param string $html A complete HTML document
  
                $this->assertEmpty( $errors, implode( "\n", $errors ) );
        }
 +
  }